package com.hugehard.endpointsearch;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.util.Log;

public class UDPServer extends Thread {
	private static final String TAG = "UDPServer";
	private DatagramSocket mServer = null;

	public UDPServer() {
		DatagramSocket tmp = null;
		try {
			tmp = new DatagramSocket(ScanTask.PORT);
		} catch (IOException e) {
			Log.e(TAG, "listen() failed", e);
		}
		mServer = tmp;
	}

	@Override
	public void run() {
		byte[] recvBuf = new byte[ScanTask.STR_CLIENT_PASS_WORD.getBytes().length * 2];
		DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
		while (true) {
			try {
				mServer.receive(recvPacket);
				String recvStr = new String(recvPacket.getData(), 0,
						recvPacket.getLength());

				if (recvStr.equals(ScanTask.STR_CLIENT_PASS_WORD)) {
					int port = recvPacket.getPort();
					InetAddress addr = recvPacket.getAddress();
					byte[] sendBuf = ScanTask.STR_SERVER_PASS_WORD.getBytes();
					DatagramPacket sendPacket = new DatagramPacket(sendBuf,
							sendBuf.length, addr, port);
					mServer.send(sendPacket);
				}
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
		}
	}

	public void cancel() {
		mServer.close();
	}
}
